import React, { useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import { Modal, Select, Input, message, Checkbox, Button } from 'antd';
import MyModal from '@/components/modal';
import Icon from '@/components/layout/Icon';
import { getBranchesApi, newBranchApi } from '@/request/gitlab';
import { getMergeBranchListApi } from '@/request/mind';
import { createMergeBranchApi } from '@/request/story';

const MergeBranch = (props, ref) => {
  const { handleCallback } = props;
  const [branches, setBranches] = useState<any[]>([]); // 分支列表
  const [open, setOpen] = useState(false);
  const [mergeBranchName, setMergeBranchName] = useState('');
  const [projectId, setProjectId] = useState<number>();
  const [v, setV] = useState('');
  const search = (input, option) => `${String(option.name)}`.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  const [curNode, setCurNode] = useState<any>({});
  const [newBranch, setNewBranch] = useState<boolean>(false);

  // 递归获取数据
  const whileGet = async (id) => {
    let result = [];
    async function anonymous(per_page, page) {
      const res: any = await getBranchesApi({ id, per_page, page });
      if (res && res.length === 100) {
        result = result.concat(res);
        let p = page;
        await anonymous(100, (p += 1));
      } else {
        result = result.concat(res);
      }
    }
    await anonymous(100, 1);
    console.log(result.length, 'result');
    return result;
  };
  // 获取某个项目的所有分支
  const getBranchesList = async (id, parentid) => {
    try {
      const existBranch: any = await getMergeBranchListApi({ parentid });
      const existBranches = existBranch.map((item) => item.branch);
      const r = await whileGet(id);
      const result = r.filter((item: any) => !existBranches.includes(item.name));
      setBranches(result);
    } catch (err: any) {
      console.log(err);
    }
  };
  const onOk = async () => {
    if (!mergeBranchName) return;
    const result: any = await createMergeBranchApi({ projectId, mergeBranchName, node: curNode.id });
    console.log(result, 'result');
    if (result) {
      message.success('操作成功');
      setOpen(false);
      // {
      //   "_id": "64c74ffebb2e6ccc046898ca",
      //   "project_id": 282,
      //   "env": "dev",
      //   "parentid": "282$dev",
      //   "branch": "develop_merge_dev",
      //   "isMergeBranch": true
      // }
      const newNode = {
        _id: result.insertedId,
        project_id: projectId,
        branch: mergeBranchName,
        env: curNode.id.split('$')[1],
        parentid: curNode.id,
        isMergeBranch: true,
      };
      handleCallback(curNode, newNode);
    }
  };

  const hanleCreateNewBranch = async () => {
    if (!projectId) {
      message.error('请先选择项目');
      return;
    }
    if (!v) {
      message.error('请输入分支名称');
      return;
    }
    const mainBranch = branches.filter((item) => item.protected)[0].name;
    const params = {
      id: projectId,
      ref: mainBranch,
      branch: v,
    };
    try {
      const res: any = await newBranchApi(params);
      if (res) {
        message.success('创建分支成功');
        setV('');
        setBranches([...branches, res]);
      }
    } catch (err: any) {
      console.log(err.message);
    }
  };

  const handleBranch = (project_id, parentid) => {
    if (!Number.isNaN(project_id)) {
      setProjectId(Number(project_id));
      getBranchesList(project_id, parentid);
    }
  };
  const onChange = (e) => {
    setV(e.target.value);
  };
  useImperativeHandle(ref, () => ({
    handleOpen(selectNode) {
      setOpen(true);
      setCurNode(selectNode);
      handleBranch(selectNode.data.props.project_id, selectNode.id);
    },
  }));
  return (
    <MyModal
      width={600}
      destroyOnClose
      title="操作合并分支"
      open={open}
      onOk={() => {
        onOk();
      }}
      onCancel={() => {
        setOpen(false);
        setMergeBranchName('');
      }}
    >
      <div>
        <Select
          style={{ width: '100%', marginTop: '20px' }}
          placeholder="请选择分支"
          options={branches}
          filterOption={search}
          showSearch
          fieldNames={{ label: 'name', value: 'name' }}
          onChange={(value) => {
            setMergeBranchName(value);
          }}
          dropdownRender={(menu) => (
            <>
              {menu}
              <div className="flex" style={{ padding: '12px 0' }}>
                <Input value={v} style={{ flex: 'auto', marginRight: '10px' }} placeholder="请输入新的分支名称" onChange={onChange} />
                <Button
                  className="flex"
                  type="primary"
                  icon={<Icon src="/images/add.png" style={{ marginRight: '4px' }} width={16} height={16} />}
                  onClick={() => {
                    hanleCreateNewBranch();
                  }}
                >
                  新建分支
                </Button>
              </div>
            </>
          )}
        ></Select>
        <div style={{ marginTop: '20px', color: '#ccc' }}>tips:创建完合并分支后请手动合并代码</div>
      </div>
    </MyModal>
  );
};

export default forwardRef(MergeBranch);
